package com.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.Result;
import com.demo.dto.UserDTO;
import com.demo.entity.Answer;
import com.demo.entity.UserFollow;
import com.demo.mapper.UserFollowMapper;
import com.demo.service.UserFollowService;
import com.demo.utils.UserHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    UserFollow getUserFollow(Integer userId, Integer targetUserId) {
        return query().eq("follower", userId)
                .eq("target", targetUserId).one();
    }

    @Override
    public Result<UserFollow> follow(Integer targetUserId) {
        Integer userId = UserHolder.getUser().getUserId();
        UserFollow userFollow = getUserFollow(userId, targetUserId);
        if (getUserFollow(userId, targetUserId) != null) {
            // 已关注，取消关注
            removeById(userFollow);
            return Result.ok(userFollow, "取消关注成功");
        }
        else {
            // 未关注，进行关注
            UserFollow userFollowInsert = new UserFollow(null, userId, targetUserId);
            try {
                save(userFollowInsert);
                return Result.ok(userFollowInsert, "添加关注成功");
            }
            catch (Exception e) {
                return Result.fail("外键错误");
            }
        }
    }

    @Override
    public Result<List<UserDTO>> getFollowingListByCurrentUserId() {
        Integer userId = UserHolder.getUser().getUserId();
        UserFollowMapper userFollowMapper = getBaseMapper();
        List<UserDTO> userDTOList = userFollowMapper.getFollowingListByUserId(userId);
        return Result.ok(userDTOList, userDTOList.size());
    }
}
